package com.hui.demo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

/**
 * security配置类
 * @author ziv
 * @date 2019-01-04
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 取消密码加密操作,正常开发时去除
     * @return
     */
    @Bean
    private static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder)NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public CustomUserService customUserService () {
        return new CustomUserService();
    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        /**
         * 路由策略和访问权限配置
         * 启用默认登录页面
         * 登录失败返回URL:/login?error
         * 登录成功跳转URL,设定为跳转到首页
         * 登录页面全部权限可访问
         */
        security.formLogin().failureUrl("/login?error").defaultSuccessUrl("/user/test").permitAll();
        super.configure(security);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(customUserService());
//        auth.inMemoryAuthentication()
//                .withUser("ziv").password("123456").roles("ADMIN")
//                .and()
//                .withUser("qing").password("123456").roles("USER");

    }
}
